package com.quanxiaoha.ai.robot.controller;

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author Caius
 * @description
 * @since Created in 2025-09-14
 */
@Slf4j
@RestController
@RequestMapping("/v11/ai")
public class Text2AudioController {

    @Value("${spring.ai.openai.api-key}")
    private String apiKey;

    @GetMapping("/text2audio")
    public String text2audio(@RequestParam(value = "prompt") String prompt) {
        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(apiKey)
                .model("cosyvoice-v2")
                .voice("longanran")
                .build();

        // 同步调用大模型，并获得字节流
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        ByteBuffer audio = synthesizer.call(prompt);

        String path = "D:\\result-audio.mp3";
        File file = new File(path);

        log.info("## resultId: {}",synthesizer.getLastRequestId());

        // 存储字节流
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(audio.array());
        } catch (IOException e) {
            log.error("", e);
        }

        return "success";
    }
}
